<template>
    <view class="container">
        <!-- 顶部标题栏 -->
        <view class="header">
            <text class="title">第 {{ roundNumber }} 局结算</text>
            <view class="divider"></view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-state">
            <uni-load-more status="loading"></uni-load-more>
        </view>
        
        <!-- 错误提示 -->
        <view v-if="error" class="error-state">
            <image src="@/static/logo.png" class="error-icon"></image>
            <text class="error-text">{{ error }}</text>
            <button class="retry-button" @click="initData">重试</button>
        </view>

        <!-- 主要内容区域 -->
        <view v-if="!loading && !error" class="content">
            <!-- 玩家结算卡片列表 -->
            <view class="member-cards">
                <view v-for="(member, userId) in currentRoomData.members" :key="userId" class="member-card">
					
					<!-- <view class="member-card"> -->
					  <!-- 调试信息 -->
					  <!-- <text>当前用户ID: {{ currentUserId }} (类型: {{ typeof currentUserId }})</text> -->
					  <!-- <text>成员user_id: {{ member.user_id }} (类型: {{ typeof member.user_id }})</text> -->
					  <!-- <text>条件结果: {{ member.user_id === currentUserId }}</text> -->
					<!-- </view> -->					
                    <!-- 玩家头像和信息 -->
                    <view class="member-info">
                        <image :src="member.avatar || defaultAvatar" class="avatar"></image>
                        <text class="member-name">{{ member.nickname }}</text>
                        <text class="role-tag" v-if="member.isWinner">赢家</text>
                    </view>
                    <!-- 分数输入区域 -->
                   <view class="score-section">
                        <text class="score-label">得分:</text>
                        <input 
                            type="number" 
                            v-model="currentRoomData.members[userId].score" 
                            placeholder="0"
                            class="score-input"
                            @focus="handleScoreFocus(userId)"
                            @blur="handleScoreBlur(userId)"
                            @input="validateScore(userId)"
                            :disabled="userId !== currentUserId || isSubmitting" 
                            :class="{ 'disabled-input': userId !== currentUserId }"
                        />
                    </view>
					
                    <!-- 赢家选择 -->
                    <view class="winner-section" v-if="String(member.user_id) === currentUserId || member.isWinner">
                        <text class="winner-label">赢家:</text>
                        <switch 
                            :checked="member.isWinner" 
                            @change="(e) => handleWinnerChange(userId, e.detail.value)"
                            color="#07C160"
                            :disabled="isSubmitting || isSelfSubmitted"
                        />
                    </view>
                </view>
            </view>
            <!-- 结算说明 -->
            <view class="settlement-info">
                <text class="info-text">结算规则：赢家获得所有非赢家支付的分数总和，非赢家支出与自身得分等额的分数</text>
            </view>
            
            <!-- 底部操作栏 -->
           <view class="action-bar">
                <button class="action-button secondary" @click="backbutton" :disabled="isSubmitting">
                    <text>取消</text>
                </button>
                
                <button 
                  class="action-button primary" 
                  @click="confirmbutton" 

                >
                  <template v-if="!isSubmitting">
                    <text >{{ submitButtonText }}</text>
                  </template>
                    <text v-else>提交中...</text>
                </button>
            </view>
			
        </view>
		
    </view>

	
</template>

<script setup>
import { ref, computed, onUnmounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { storeToRefs } from 'pinia';
import { useSocketStore } from '@/stores/modules/socketStore.js';

// 默认头像
const defaultAvatar = 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png';
// 状态管理实例
const socketStore = useSocketStore();
// 从 socketStore 中解构所需的响应式状态
const { 
	connectionState, 
	roomData } = storeToRefs(socketStore);

// 响应式数据（仅保留currentRoomData作为核心数据源）
const currentRoomData = ref({
    members: {
		// user_id: {
		// 	user_id:0,
		//     avatar: '',
		//     nickname: '',
		// 	score:0,
		// 	isWinner:false
		// }
	},
    settlement: {
        roundNumber: 0,
        submittedUsers: [],
        scores: {},
        isCompleted: false
    }
});
const roomId = ref('');            // 房间ID，从url中接出来
const roundNumber = ref(0);        // 当前回合数

const loading = ref(true);         // 加载状态
const error = ref(null);           // 错误信息

const isSubmitting = ref(false);   // 提交状态,用于控制按钮显示
// const submissionStatus = ref({});  // 提交状态跟踪
const currentUserId = ref('');     // 当前用户ID




// 计算属性：只读不改
// 当前结算数据：改的话直接改roomdata就行
const currentSettlement = computed(() => {
    if (!currentRoomData.value.settlement) {
        currentRoomData.value.settlement = {
            roundNumber: roundNumber.value,
            submittedUsers: [],
            scores: {},
            isCompleted: false
        };
    }
    return currentRoomData.value.settlement;
})


// 已提交人数（直接从currentRoomData计算）
const submittedCount = computed(() => currentSettlement.value.submittedUsers.length);

// 房间总人数（直接从currentRoomData计算）
const totalCount = computed(() => Object.keys(currentRoomData.value.members).length);

// 自己是否已提交
const isSelfSubmitted = computed(() => currentRoomData.value.settlement.submittedUsers.includes(currentUserId.value));

// 是否所有分数都已填写
const allScoresFilled = computed(() => {
    const members = currentRoomData.value.members;
    return Object.keys(members).every(userId => {
        const score = members[userId].score;
        return score !== '' && !isNaN(parseInt(score)) && parseInt(score) >= 0;
    });
});

// 验证是否已选择赢家
const hasWinner = computed(() => {
    const members = currentRoomData.value.members;
    return Object.keys(members).some(userId => members[userId].isWinner);
});

// 提交按钮文本（动态变化）
const submitButtonText = computed(() => {
  if (currentSettlement.value.isCompleted) return "全部已提交";
  if (isSelfSubmitted.value) return `等待中(${submittedCount.value}/${totalCount.value})`;
  return "确认提交";
});






/**
 * 页面加载时初始化
 */
onLoad((options) => {
    roomId.value = options.roomId;
    roundNumber.value = parseInt(options.roundNumber) || 0;

    // 直接监听roomData变化，同步到currentRoomData
    watch(
        () => roomData.value[roomId.value],
        (newRoomData) => {
            if (newRoomData) {
                currentRoomData.value = { ...newRoomData };
                // 确保members和settlement结构存在
                if (!currentRoomData.value.members) currentRoomData.value.members = {};
                if (!currentRoomData.value.settlement) currentRoomData.value.settlement = {
                    roundNumber: roundNumber.value,
                    submittedUsers: [],
                    scores: {},
                    isCompleted: false
                };
            }
        },
        { deep: true, immediate: true }
    );
    
    // 检查Socket连接状态
    if (connectionState.value !== 'connected' || !socketStore.isConnectedToRoom(roomId.value)) {
        socketStore.connect(roomId.value);
    } 
    initData();
});
/**
 * 初始化数据 - 从 socketStore.roomData 获取玩家信息（核心修正点）
 */
const initData = async () => {
  try {
    loading.value = true;
    error.value = null;
    // 1. 获取当前用户ID
    const userStr = uni.getStorageSync('user') || '{}';
    const user = JSON.parse(userStr);
    currentUserId.value = String(user.userinfo?.userid || '');
    
    // 2. 检查房间数据是否存在
    if (!currentRoomData.value ) {
      throw new Error('房间数据不存在，请重新进入房间');
    }
	// 3. 初始化成员列表
        Object.keys(currentRoomData.value.members).forEach(userId => {
            const member = currentRoomData.value.members[userId];
            // 确保score是字符串类型（适配input）
            if (member.score === undefined) member.score = "0";
            else member.score = String(member.score);
            // 确保isWinner存在
            if (member.isWinner === undefined) member.isWinner = false;
        });
    // 4. 注册Socket事件监听
    registerSocketListeners();
    } catch (err) {
        error.value = err.message || '加载数据失败，请稍后重试';
        console.error('初始化数据出错:', err);
    } finally {
        loading.value = false;
    }
	// member.userId === currentUserId
	// console.log('当前用户ID：', currentUserId.value);
	// console.log('成员列表结构：', currentRoomData.value.members);
};

// 聚焦操作：当输入框获得焦点（用户点击输入框准备输入时）。如果当前分数是默认的 “0”，则清空输入框，方便用户直接输入新数值（避免手动删除 “0” 的操作）。
const handleScoreFocus = (userId) => {
    if (userId !== currentUserId.value) return;
    
    const member = currentRoomData.value.members[userId];
    // 聚焦时若为默认0，则清空
    if (member.score === "0") {
        member.score = "";
    }
};
// 失焦操作：当输入框失去焦点（用户完成输入并点击其他区域时）。如果用户未输入任何内容（输入框为空），则自动恢复为默认值 “0”，避免分数为空的无效状态。
const handleScoreBlur = (userId) => {
    if (userId !== currentUserId.value) return;
    
    const member = currentRoomData.value.members[userId];
    // 失焦时若为空，重置为0
    if (member.score.trim() === "") {
        member.score = "0";
    } else {
        // 同步为数字类型到原始数据
        member.score = String(parseInt(member.score) || 0);
    }
};
/**
 * 分数输入验证
 */
const validateScore = (userId) => {
    if (userId !== currentUserId.value) return;
    
    const member = currentRoomData.value.members[userId];
    // 仅保留数字
    let validated = member.score.replace(/[^\d]/g, "");
    // 限制最大值500
    if (validated && parseInt(validated) > 500) {
        validated = "500";
    }
    member.score = validated;
};


/**
 * 处理赢家状态变更
 */
const handleWinnerChange = (userId, isWinner) => {
    if (userId !== currentUserId.value) return;
    
    // 重置其他人的赢家状态
    Object.keys(currentRoomData.value.members).forEach(otherUserId => {
        if (otherUserId !== userId) {
            currentRoomData.value.members[otherUserId].isWinner = false;
        }
    });
    
    // 设置当前用户的赢家状态
    currentRoomData.value.members[userId].isWinner = isWinner;
    
    if (isWinner) {
        uni.showToast({
            title: '温馨提示：赢家底分为20',
            icon: 'none',
            duration: 1500
        });
    }
};




// 还有一种方案就是:不要settlement了,通过计算属性构造一个settlement出来,每次提交都通过一个settlement时间进行,同时构造一个监听事件,同步解析这个settlement到各个数据路径  进而更新页面

/**
 * 注册Socket事件监听
 */
const registerSocketListeners = () => {
  // 监听其他玩家的分数和赢家状态更新
    // socketStore.on('score_updated', (data) => {
    //     if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
        
    //     const { user_id, score, isWinner } = data;
    //     if (currentRoomData.value.members[user_id] && user_id !== currentUserId.value) {
    //         currentRoomData.value.members[user_id].score = String(score);
    //         currentRoomData.value.members[user_id].isWinner = isWinner;
    //     }
    // });
	// 监听成员提交状态
	// socketStore.on('member_submitted', (data) => {
	//     if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
	//         if (!currentSettlement.value.submittedUsers.includes(data.user_id)) {
	//             currentSettlement.value.submittedUsers.push(data.user_id);
	//         }
	//     }
	// });
	// socketStore.on('final_submission', () => {
	//   if (!isSubmitting.value) {
	// 	realSubmitToBackend(); // 实际提交到后端
	//   }
	// });
    // 监听其他玩家的结算数据更新
    // socketStore.on('roundpay_update', (data) => {
    //     if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;
    //     data.members.forEach(remoteMember => {
    //         const userId = String(remoteMember.userId);
    //         if (currentRoomData.value.members[userId] && userId !== currentUserId.value) {
    //             currentRoomData.value.members[userId].score = String(remoteMember.score);
    //             currentRoomData.value.members[userId].isWinner = remoteMember.isWinner;
    //         }
    //     });
    // });
    // 监听结算完成事件
    socketStore.on('settlement_completed', (data) => {
		console.log("settlement_completed监听成功")
        if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
            // uni.showToast({ title: '本局结算已完成' });
            // setTimeout(() => uni.navigateBack(), 1500);
        }
    });
	
	
	
	
	
	
	
	
    // 监听其他人提交的分数
    socketStore.on('user_score_submitted', (data) => {
  		// console.log("执行user_score_submitted前")
		// const { room_id: roomId, roundNumber, user_id, score, isWinner } = data;
  		// console.log("执行user_score_submitted中data",data)
        if (data.room_id !== roomId.value || data.roundNumber !== roundNumber.value) return;     
        const { userId, score, isWinner,submittedUsers } = data;
		
        if (currentRoomData.value.members[userId]) {
            currentRoomData.value.members[userId].score = String(score);
            currentRoomData.value.members[userId].isWinner = isWinner;
            currentRoomData.value.settlement.scores[userId] = { userId,score, isWinner };
			currentRoomData.value.settlement.submittedUsers=submittedUsers;
        }
		// console.log("开始处理监听：",roomData.value)
		
		// 记录当前用户已提交
		// if (!currentRoomData.value.settlement.submittedUsers.includes(currentUserId.value)) {
		// 	console.log("push进入列表前：",roomData.value)
		//     currentRoomData.value.settlement.submittedUsers.push(currentUserId.value);
		// 	console.log("处理完成：",roomData.value)
		// }
		// else{
		// 	console.log("无需push用户已存在：",roomData.value)
		// }
		// console.log("执行user_score_submitted后")
		// console.log("执行roomdata后：",roomData.value)
    });
  
    // 监听全部完成事件
    socketStore.on('settlement_all_completed', (data) => {
		console.log("监听到settlement_all_completed")
        if (data.room_id === roomId.value && data.roundNumber === roundNumber.value) {
            uni.showToast({ title: '所有人已提交，正在结算...' });
            setTimeout(() => uni.navigateBack(), 1500);
        }
    });
};





/**
 * 提交结算数据
 * 结算步骤：前三人结算更新消息并存入settelment，第四人结算整合数据发送后端，
 */
const confirmbutton = async () => {
	//提交前判断 是否选择赢家，是否所有人都填写
	// console.log(members.value)
  try {
    isSubmitting.value = true;
    // 获取当前用户数据
    const currentUser = currentRoomData.value.members[currentUserId.value];
    if (!currentUser) throw new Error('未找到当前用户数据');
    
	// if (!allScoresFilled.value) {
    //   uni.showToast({ title: '请填写所有玩家分数', icon: 'none' });
    //   return;
    // }
    // if (!hasWinner.value) {
    //   uni.showToast({ title: '本轮提交至少选择一个赢家', icon: 'none' });
    //   return;
    // }
	
	
	
	if (!currentRoomData.value.settlement.submittedUsers.includes(currentUserId.value)) {
		// console.log("push进入列表前：",roomData.value)
	    currentRoomData.value.settlement.submittedUsers.push(currentUserId.value);
		// console.log("处理完成：",roomData.value)
	}
	else{
		console.log("无需push用户已存在：",roomData.value)
	}

    // 广播当前用户的分数
    socketStore.emit('user_score_submit', {
            room_id: roomId.value,
            roundNumber: roundNumber.value,
            user_id: currentUserId.value,
            score: parseInt(currentUser.score) || 0,
            isWinner: currentUser.isWinner,
			submittedUsers:currentRoomData.value.settlement.submittedUsers
    });
        // 记录当前用户已提交
        // if (!currentSettlement.value.submittedUsers.includes(currentUserId.value)) {
            // currentSettlement.value.submittedUsers.push(currentUserId.value);
        // }
		
        // 检查是否是最后一个提交的人
        const newSubmittedCount = submittedCount.value;
        if (newSubmittedCount === totalCount.value) {
			console.log("最后一个人")
            // 最后一个人负责提交到后端
            await submitToBackend();
        } else {
            // 不是最后一个，只显示等待
			console.log("不是最后一个人")
            uni.showToast({ title: `已提交，等待其他${totalCount.value - newSubmittedCount}人` });
        }
    } catch (err) {
        uni.showToast({ title: err.message || '提交失败', icon: 'none' });
    } finally {
        isSubmitting.value = false;
    }
};
	

/**
 * 提交到后端
 */
const submitToBackend = async () => {
    try {
        // 收集所有人的分数（直接从currentRoomData获取）   这里要做校验  赢家  四个人？
        // const membersData = Object.keys(currentRoomData.value.members).map(userId => ({
        //     userId,
        //     score: parseInt(currentRoomData.value.members[userId].score) || 0,
        //     isWinner: currentRoomData.value.members[userId].isWinner
        // }));

		// console.log("currentRoomData.settlement.scores.value***",currentRoomData.settlement.scores.value)
		
        // 准备提交数据
		console.log("currentRoomData***",currentRoomData.value.members)
		// 正确代码：通过键名获取用户对象
		const membersData = Object.keys(currentRoomData.value.members).map(userId => {
		  const member = currentRoomData.value.members[userId]; // 根据键名获取用户对象
		  return {
		    userId: member.user_id,  // 从用户对象中提取 user_id（注意字段名是 user_id 而非 userId）
		    score: parseInt(member.score) || 0,
		    isWinner: member.isWinner
		  };
		});
    //     const submitData = {
    //       roomId: roomId.value,
    //       roundNumber: roundNumber.value,
    //       // players: currentRoomData.value.members.map(p => ({ 
    //       //   userId: p.userId,
    //       //   score: parseInt(p.score)||0,
    //       //   isWinner: p.isWinner
    //       // }))
		  // players: membersData
		  
    //     };
		// console.log("，*-*-*-*-",submitData)
        const res = await uni.request({
            url: 'http://172.16.24.120:5000/mysqlroom/rounds/settle',
            method: 'POST',
            data: {
                roomId: roomId.value,
                roundNumber: roundNumber.value,
                players: membersData
            }
        });
        
        if (res.statusCode === 200) {
            // 标记结算完成
            currentRoomData.value.settlement.isCompleted = true;
            // 广播给所有人：全部提交完成
            socketStore.emit('settlement_all_complet', {
                room_id: roomId.value,
                roundNumber: roundNumber.value
            });
            uni.showToast({ title: '结算成功' });
			
			
			
			// 清空members的输入分数与赢家状态
			// 清除
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
            setTimeout(() => uni.navigateBack(), 1500);
        } else {
            throw new Error('保存到服务器失败');
        }
    } catch (err) {
        console.error('最终提交失败:', err);
        uni.showToast({ title: '结算失败，请重试', icon: 'none' });
    }
};


/**
 * 返回按钮处理
 */
const backbutton = () => {
  uni.navigateBack();
};

/**
 * 组件卸载时清理
 */
onUnmounted(() => {
  // socketStore.off('score_updated');//灭有
  // socketStore.off('roundpay_update');
  socketStore.off('settlement_completed');//结算
  // socketStore.off('member_submitted');//没有
  // socketStore.off('final_submission');//没有
  socketStore.off('user_score_submitted');
  socketStore.off('settlement_all_completed');
});

/**
 * 监听Socket连接状态变化
 */
watch(connectionState, (newState) => {
  if (newState === 'disconnected' && !loading.value && !error.value) {
    error.value = '连接已断开，请重试';
  }
});
</script>

<style scoped>
/* 全局容器样式 */
.container {
    padding: 0;
    background-color: #f8f8f8;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}
/* 头部样式 */
.header {
    padding: 20px 16px 12px;
    background-color: #ffffff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
    text-align: center;
}

.divider {
    height: 1px;
    background-color: #eee;
    margin-top: 12px;
}

/* 加载状态样式 */
.loading-state {
    padding: 40px 0;
    display: flex;
    justify-content: center;
}

/* 错误状态样式 */
.error-state {
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.error-icon {
    width: 60px;
    height: 60px;
    margin-bottom: 16px;
}

.error-text {
    font-size: 16px;
    color: #ff4d4f;
    margin-bottom: 20px;
    text-align: center;
}

.retry-button {
    background-color: #1890ff;
    color: white;
    border: none;
    border-radius: 20px;
    padding: 8px 24px;
    font-size: 14px;
}

/* 主要内容区域 */
.content {
    flex: 1;
    padding: 16px;
    display: flex;
    flex-direction: column;
}

/* 结算说明 */
.settlement-info {
    padding: 12px 16px;
    background-color: #fff8e6;
    border-radius: 8px;
    margin: 10px 0;
}

.info-text {
    font-size: 14px;
    color: #e6a23c;
    line-height: 1.5;
}

/* 玩家卡片列表 */
.member-cards {
    flex: 1;
}

.member-card {
    background-color: #fff;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 12px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.member-info {
    display: flex;
    align-items: center;
    flex: 1;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 12px;
}

.member-name {
    font-size: 16px;
    color: #333;
    font-weight: 500;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
}

.role-tag {
    background-color: #07C160;
    color: white;
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 12px;
    margin-left: 8px;
}

/* 分数输入区域 */
.score-section {
    display: flex;
    align-items: center;
    margin: 0 16px;
}

.score-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.score-input {
    width: 80px;
    height: 36px;
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 0 10px;
    text-align: center;
    font-size: 16px;
    color: #333;
    background-color: #f9f9f9;
}

/* 赢家选择区域 */
.winner-section {
    display: flex;
    align-items: center;
}

.winner-label {
    font-size: 14px;
    color: #666;
    margin-right: 8px;
}

.winner-switch {
    transform: scale(0.8);
}

/* 底部操作栏 */
.action-bar {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    background-color: #fff;
    border-top: 1px solid #eee;
    position: sticky;
    bottom: 0;
}

.action-button {
    flex: 1;
    height: 48px;
    border-radius: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-weight: 500;
    transition: all 0.3s;
}

.action-button.secondary {
    background-color: #f5f5f5;
    color: #666;
    margin-right: 12px;
}

.action-button.secondary:active {
    background-color: #e5e5e5;
}

.action-button.primary {
    background-color: #07C160;
    color: white;
}

.action-button.primary:disabled {
    background-color: #a0d7b8;
    opacity: 0.7;
}

.action-button.primary:active:not(:disabled) {
    background-color: #05a14e;
}

/* 非当前用户的输入框样式 */
.disabled-input {
  background-color: #f0f0f0;
  color: #999;
  cursor: not-allowed;
}
</style>